﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using SPMS.Common;
using SPMS.Data;
using SPMS.Web.Models;
using SPMS.Web.Mvc;

namespace SPMS.Web.Controllers
{
    /// <summary>
    /// 封装形式数据字典控制器
    /// </summary>
    [AuthorizeEx]
    public class PackagingController : Controller
    {
        #region ---Views

        /// <summary>
        /// 默认视图动作.
        /// </summary>
        /// <returns>视图结果。</returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获得封装方式详细视图。
        /// </summary>
        /// <param name="model">封装方式查询模型。</param>
        /// <returns>执行结果。</returns>
        public ActionResult DetailView(PackagingQueryModel model)
        {
            //用于保存实体
            Packaging entity = null;

            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //查询数据
                entity = context.Packagings.Include("PackagingImages").FirstOrDefault(item => item.Packaging_ID == model.Packaging_ID);
            }

            //判断实体是否存在
            if (null == entity)
            {
                //重定向
                return PartialView("_EntityNotFoundPartial");
            }

            //返回视图
            return PartialView(entity);
        }

        #endregion

        #region ---Action

        /// <summary>
        /// 创建封装形式。
        /// </summary>
        /// <param name="model">封装形式数据字典。</param>
        /// <returns>操作执行结果。</returns>
        [JsonHandleError]
        public ActionResult Create(PackagingModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //判断同名封装形式是否已经存在
                if (context.Packagings.Any(item => item.Packaging_Name == model.Packaging_Name))
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的封装形式已经存在，封装形式的名称不允许重复。<br/>请将封装形式的名称指定为其它名称。", model.Packaging_Name));
                }

                //创建实体
                Packaging entity = new Packaging()
                {
                    Packaging_ID = Guid.NewGuid(),
                    Packaging_Abbr = model.Packaging_Abbr,
                    Packaging_Name = model.Packaging_Name,
                    Memo = model.Memo
                };

                //添加实体
                context.Packagings.Add(entity);

                //判断是否上传了图片
                if (null != model.Images && model.Images.Length > 0)
                {
                    //获得存储路径
                    string repositoryPath = this.GetRepositoryPath();

                    //用于保存图片名称名称
                    string imageFilePath = string.Empty;

                    //循环添加照片
                    foreach (UploadFileModel item in model.Images)
                    {
                        //创建实体
                        PackagingImage image = new PackagingImage()
                        {
                            Image_ID = item.File_ID,
                            Image_Title = item.File_Title,
                            Image_Desc = item.File_Desc,
                            Packaging_ID = entity.Packaging_ID
                        };

                        //生成图片文件路径
                        imageFilePath = Path.Combine(repositoryPath, image.Packaging_ID.ToString("B"), string.Format("{0:B}.jpeg", image.Image_ID));

                        //准备路径
                        IOHelper.PrepareFilePath(imageFilePath);

                        //准备路径
                        //将临时文件移动为图片
                        FileUploadHelper.CopyTempFileToImage(context, item.File_ID, IMAGE_WIDTH, IMAGE_HEIGHT, 0.0f, ImageFormat.Jpeg, imageFilePath, true);

                        //添加图片
                        context.PackagingImages.Add(image);
                    }
                }

                //启动事务
                using (TransactionScope transaction = new TransactionScope())
                {
                    //保存变化
                    context.SaveChanges();

                    //提交事务
                    transaction.Complete();
                }

                //删除临时文件
                if (null != model.Images)
                {
                    //循环添加照片
                    foreach (UploadFileModel item in model.Images)
                    {
                        //删除临时文件
                        FileUploadHelper.DeleteTempFile(item.File_ID);
                    }
                }
            }

            //返回结果
            return this.JsonEx();
        }

        /// <summary>
        /// 更新封装形式。
        /// </summary>
        /// <param name="model">封装形式数据字典。</param>
        /// <returns>操作执行结果。</returns>
        [JsonHandleError]
        public ActionResult Update(PackagingModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //判断同名封装形式是否已经存在
                if (context.Packagings.Any(item => item.Packaging_Name == model.Packaging_Name && item.Packaging_ID != model.Packaging_ID))
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的封装形式已经存在，封装形式的名称不允许重复。<br/>请将封装形式的名称指定为其它名称。", model.Packaging_Name));
                }

                //获得账户信息
                Packaging entity = context.Packagings.Include("PackagingImages").FirstOrDefault(item => item.Packaging_ID == model.Packaging_ID);

                //判断是否存在
                if (null == entity)
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的封装形式不存在，无法更新。<br/>请确认此封装形式是否已经被删除。", model.Packaging_Name));
                }

                //更新实体
                entity.Packaging_Name = model.Packaging_Name;
                entity.Packaging_Abbr = model.Packaging_Abbr;
                entity.Memo = model.Memo;

                //用于保存文件编号
                Dictionary<Guid, UploadFileModel> tempFiles = new Dictionary<Guid, UploadFileModel>();

                //用于保存要删除的图片
                List<PackagingImage> deleteImages = new List<PackagingImage>();

                //获得存储路径
                string repositoryPath = this.GetRepositoryPath();

                //用于保存图片名称名称
                string imageFilePath = string.Empty;

                //用于保存缩略图片名称名称
                string imageThumbFilePath = string.Empty;

                //判断是否上传了图片
                if (null != model.Images && model.Images.Length > 0)
                {
                    //循环添加照片
                    foreach (UploadFileModel item in model.Images)
                    {
                        //保存文件编号
                        tempFiles.Add(item.File_ID, item);

                        //判断是否为新增
                        if (item.IsNew)
                        {
                            //创建实体
                            PackagingImage image = new PackagingImage()
                            {
                                Image_ID = item.File_ID,
                                Image_Title = item.File_Title,
                                Image_Desc = item.File_Desc,
                                Packaging_ID = entity.Packaging_ID
                            };

                            //生成图片文件路径
                            imageFilePath = Path.Combine(repositoryPath, image.Packaging_ID.ToString("B"), string.Format("{0:B}.jpeg", image.Image_ID));

                            //准备路径
                            IOHelper.PrepareFilePath(imageFilePath);

                            //将临时文件移动为图片
                            FileUploadHelper.CopyTempFileToImage(context, item.File_ID, IMAGE_WIDTH, IMAGE_HEIGHT, 0.0f, ImageFormat.Jpeg, imageFilePath, true);

                            //添加图片
                            context.PackagingImages.Add(image);
                        }
                    }
                }

                //判断是否需要删除
                if (entity.PackagingImages != null && entity.PackagingImages.Count > 0)
                {
                    //用于保存文件对象
                    UploadFileModel fileItem = null;

                    //判断是否存在
                    foreach (PackagingImage item in entity.PackagingImages.ToArray())
                    {
                        //判断是否存在
                        if (!tempFiles.TryGetValue(item.Image_ID, out fileItem))
                        {
                            //添加到删除文件列表
                            deleteImages.Add(item);

                            //如果不存在，则删除
                            context.PackagingImages.Remove(item);
                        }
                        else
                        {
                            //更新数据
                            item.Image_Title = fileItem.File_Title;
                            item.Image_Desc = fileItem.File_Desc;
                        }
                    }
                }

                //启动事务
                using (TransactionScope transaction = new TransactionScope())
                {
                    //保存变化
                    context.SaveChanges();

                    //提交事务
                    transaction.Complete();
                }

                //删除图片
                if (null != model.Images)
                {
                    //循环添加照片
                    foreach (PackagingImage item in deleteImages)
                    {
                        //生成图片文件路径
                        imageFilePath = Path.Combine(repositoryPath, item.Packaging_ID.ToString("B"), string.Format("{0:B}.jpeg", item.Image_ID));

                        //删除文件
                        IOHelper.SafeDeleteFile(imageFilePath);

                        //生成缩略图片文件路径
                        imageThumbFilePath = Path.Combine(repositoryPath, item.Packaging_ID.ToString("B"), string.Format("{0:B}_thumb.jpeg", item.Image_ID));

                        //删除文件
                        IOHelper.SafeDeleteFile(imageThumbFilePath);
                    }
                }
            }

            //返回结果
            return this.JsonEx();
        }

        /// <summary>
        /// 删除封装方式。
        /// </summary>
        /// <param name="model">要删除的封装方式。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [JsonHandleError]
        public ActionResult Delete(PackagingModel model)
        {
            //判断模型是否有效
            if (null == model)
            {
                //直接返回
                return this.JsonEx();
            }

            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //获得账户信息
                var entity = context.Packagings.Include("PackagingImages").FirstOrDefault(item => item.Packaging_ID == model.Packaging_ID);

                //判断指定的账户是否存在
                if (null != entity)
                {
                    //获得存储路径
                    string repositoryPath = this.GetRepositoryPath();

                    //用于保存图片文件夹路径
                    string imageFolderPath = string.Empty;

                    //用于保存图片
                    PackagingImage[] images = null;

                    //判断是否有照片
                    if (entity.PackagingImages != null && entity.PackagingImages.Count > 0)
                    {
                        //获得图片
                        images = entity.PackagingImages.ToArray();

                        //循环删除照片
                        foreach (PackagingImage item in images)
                        {
                            //删除
                            context.PackagingImages.Remove(item);
                        }
                    }

                    //删除
                    context.Packagings.Remove(entity);

                    //启动事务
                    using (TransactionScope transaction = new TransactionScope())
                    {
                        //保存变化
                        context.SaveChanges();

                        //提交事务
                        transaction.Complete();
                    }

                    //删除图片
                    if (null != images)
                    {
                        //循环添加照片
                        foreach (PackagingImage item in images)
                        {
                            //生成图片文件夹路径
                            imageFolderPath = Path.Combine(repositoryPath, item.Packaging_ID.ToString("B"));

                            //删除文件夹
                            IOHelper.SafeDeleteFolder(imageFolderPath);
                        }
                    }
                }

                //返回结果
                return this.JsonEx();
            }
        }

        /// <summary>
        /// 获得封装形式列表。
        /// </summary>
        /// <param name="queryModel">查询模型对象。</param>
        /// <returns>动作结果。</returns>
        [JsonHandleError]
        public JsonResult List(JsonPagingQueryModel queryModel)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //用于保存总记录数
                int totalRecord = 0;

                //查询数据
                var query = from item in context.Packagings.QueryData(queryModel, out totalRecord)
                            select new
                            {
                                item.Packaging_ID,
                                item.Packaging_Abbr,
                                item.Packaging_Name,
                                item.Memo
                            };

                //获得数据
                var data = query.ToArray();

                //返回数据
                return new JsonResultEx
                (
                    new JsonResultViewModel()
                    {
                        success = true,
                        data = data,
                        total = totalRecord
                    },
                    JsonRequestBehavior.AllowGet
                );
            }
        }

        /// <summary>
        /// 获得封装方式详细信息。
        /// </summary>
        /// <param name="model">封装方式查询模型。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [JsonHandleError]
        public ActionResult Detail(PackagingQueryModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //查询数据
                var entity = context.Packagings.FirstOrDefault(item => item.Packaging_ID == model.Packaging_ID);

                //判断是否有数据
                if (null == entity)
                {
                    //返回结果
                    return this.JsonEx(false, string.Format("名为'{0}'的封装方式信息不存在。<br/>请确认此封装方式是否已经被删除。", model.Packaging_Name));
                }

                //创建数据
                var data = new
                {
                    entity.Packaging_ID,
                    entity.Packaging_Abbr,
                    entity.Packaging_Name,
                    entity.Memo
                };

                //返回数据
                return this.JsonEx(true, data, 1);
            }
        }

        /// <summary>
        /// 获得封装方式图片信息。
        /// </summary>
        /// <param name="model">封装方式查询模型。</param>
        /// <returns>
        /// 执行结果。
        /// </returns>
        [JsonHandleError]
        public ActionResult Images(PackagingQueryModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //查询图片
                var query = from image in context.PackagingImages
                            where image.Packaging_ID == model.Packaging_ID
                            select new
                            {
                                File_ID = image.Image_ID,
                                File_Title = image.Image_Title,
                                File_Desc = image.Image_Desc,
                                HasContent = true,
                                IsNew = false,
                            };

                //获得数据
                var data = query.ToArray();

                //返回数据
                return this.JsonEx(true, data, data.Length);
            }
        }

        /// <summary>
        /// 获得封装图片。
        /// </summary>
        /// <param name="userID">文件查询模型。</param>
        /// <r
        /// eturns>图片内容。</returns>
        public ActionResult GetImage(UploadFileModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //图片格式
                ImageFormat format = ImageFormat.Jpeg;

                //获得扩展名
                string extension = FileUploadHelper.GetImageExtension(format);

                //判断是否为新增图片
                if (model.IsNew)
                {
                    //获得临时图片文件数据
                    byte[] imageData = FileUploadHelper.GetTempImage(model.File_ID, IMAGE_PREVIEW_WIDTH, IMAGE_PREVIEW_HEIGHT, format);

                    //返回文件结果
                    return this.File(imageData, FileUploadHelper.GetImageMIME(format), Path.Combine("Preview", extension));
                }
                else
                {
                    //查询数据
                    var entity = context.PackagingImages.FirstOrDefault(item => item.Image_ID == model.File_ID);

                    //判断是否有数据
                    if (null == entity)
                    {
                        //返回结果
                        return null;
                    }

                    //获得存储路径
                    string repositoryPath = this.GetRepositoryPath();

                    //生成图片文件路径
                    string imageFilePath = Path.Combine(repositoryPath, entity.Packaging_ID.ToString("B"), string.Format("{0:B}.jpeg", entity.Image_ID));

                    //返回文件结果
                    return this.File(imageFilePath, FileUploadHelper.GetImageMIME(ImageFormat.Png), "Preview.png");
                }
            }
        }

        /// <summary>
        /// 获得封装缩略图片。
        /// </summary>
        /// <param name="userID">文件查询模型。</param>
        /// <r
        /// eturns>图片内容。</returns>
        public ActionResult GetThumbnails(UploadFileModel model)
        {
            //创建上下文
            using (AccountFileManagementEntities context = new AccountFileManagementEntities())
            {
                //查询数据
                var entity = context.PackagingImages.FirstOrDefault(item => item.Image_ID == model.File_ID);

                //判断是否有数据
                if (null == entity)
                {
                    //返回结果
                    return null;
                }

                //获得存储路径
                string repositoryPath = this.GetRepositoryPath();

                //生成图片文件路径
                string imageFilePath = Path.Combine(repositoryPath, entity.Packaging_ID.ToString("B"), string.Format("{0:B}_thumb.jpeg", entity.Image_ID));

                //返回文件结果
                return this.File(imageFilePath, FileUploadHelper.GetImageMIME(ImageFormat.Png), "Thumbnails.png");
            }
        }

        #endregion

        #region ---Private Method

        /// <summary>
        /// 获得图片文件存储路径。
        /// </summary>
        /// <returns>图片文件存储路径。</returns>
        private string GetRepositoryPath()
        {
            //判断路径是否已经初始化
            if (string.IsNullOrEmpty(s_PackagingImagesRepositoryPath))
            {
                //获得路径
                s_PackagingImagesRepositoryPath = Path.Combine(FileUploadHelper.GetRepositoryPath(), FOLDER_PACKAGINGIMAGES);
            }

            //返回路径
            return s_PackagingImagesRepositoryPath;
        }

        #endregion

        #region ---Const

        /// <summary>
        /// 封装方式图片存储路径
        /// </summary>
        private static string s_PackagingImagesRepositoryPath = null;

        /// <summary>
        /// 封装方式图片存储文件夹
        /// </summary>
        private const string FOLDER_PACKAGINGIMAGES = "Packaging";

        /// <summary>
        /// 图片宽度。
        /// </summary>
        private const int IMAGE_WIDTH = 1024;

        /// <summary>
        /// 图片高度。
        /// </summary>
        private const int IMAGE_HEIGHT = 1024;

        /// <summary>
        /// 图片宽度。
        /// </summary>
        private const int IMAGE_PREVIEW_WIDTH = 360;

        /// <summary>
        /// 图片高度。
        /// </summary>
        private const int IMAGE_PREVIEW_HEIGHT = 360;

        #endregion
    }
}
